/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#if defined(WIN32) && !defined(__MINGW32__)
#include <IO.h>
#endif

#include <fcntl.h>

#include "contributors.h"
#include "global.h"
#include "configfile.h"


mapping_t Map[] =
{
    {"ProfileID"              , &configinput.profile_id           , 0}  ,
    {"LevelID"                , &configinput.level_id             , 0}  ,
    {"IntraPeriod"            , &configinput.intra_period         , 0}  ,
    {"VECPeriod"              , &configinput.vec_period           , 0}  ,
    {"SeqHeaderPeriod"        , &configinput.seqheader_period     , 0}  ,
    {"FramesToBeEncoded"      , &configinput.no_frames            , 0}  ,
    {"QPFirstFrame"           , &configinput.qp_first             , 0}  ,
    {"QPRemainingFrame"       , &configinput.qp_p                 , 0}  ,
    {"FrameSkip"              , &configinput.jumpd                , 0}  ,
    {"SearchRange"            , &configinput.search_range         , 0}  ,
    {"SourceWidth"            , &configinput.img_width            , 0}  ,
    {"SourceHeight"           , &configinput.img_height           , 0}  ,
    {"InputFile"              , &configinput.in_file              , 1}  ,
    {"InputHeaderLength"      , &configinput.infile_header        , 0}  ,
    {"OutputFile"             , &configinput.out_file             , 1}  ,
    {"ReconFile"             , &configinput.recon_file           , 1}  ,
    {"TraceFile"             , &configinput.trace_file           , 1}  ,
    {"NumberBFrames"          , &configinput.succe_b              , 0}  ,
    {"QPBPicture"             , &configinput.qp_b                 , 0}  ,
    {"inter_search_16x16"     , &configinput.inter_search_16x16   , 0}  ,
#ifdef OPT_HP
	{"HierarchicalP",           &configinput.hp_coding, 0},
#endif
    //{"inter_search_16x8"      , &configinput.inter_search_16x8    , 0}  ,
    //{"inter_search_8x16"      , &configinput.inter_search_8x16    , 0}  ,
    {"inter_search_8x8"       , &configinput.inter_search_8x8     , 0}  ,
    {"RDOptimization"         , &configinput.rdopt                , 0}  ,
    //{"Progressive_frame"      , &configinput.progressive_frame    , 0}  ,
    {"Dct_Adaptive_Flag"      , &configinput.dct_adaptive_flag    , 0}  ,
    {"SliceMode"              , &configinput.slice_mode           , 0}  ,
    {"NumberOfRowsInSlice"    , &configinput.slice_row_nr         , 0}  ,
    {"WeightEnable"           , &configinput.slice_weight_flag    , 0}  ,
    {"FrameRate"              , &configinput.frame_rate_code      , 0}  ,
    {"ChromaFormat"           , &configinput.chroma_format        , 0}  ,
    {"RateControlEnable"      , &configinput.rc_enable            , 0}  ,
    {"Bitrate"                , &configinput.bit_rate             , 0}  ,
    {"InitialQP"              , &configinput.init_qp              , 0}  ,
    {"basic_unit"             , &configinput.basic_unit           , 0}  ,
    {"ChannelType"            , &configinput.channel_type         , 0}  ,
    {"bbs_size"               , &configinput.bbs_size             , 0}  ,
    {"BbvMode"                , &configinput.bbv_mode             , 0}  ,
    {"SkipMode"               , &configinput.skip_mode_flag       , 0}  ,
    {"BiPredMotionEstimation" , &configinput.bi_me                , 0}  ,
    {"BiPredMERefinements"    , &configinput.bi_me_refine         , 0}  ,
    {"ABTEnable"        , &configinput.ABTen                , 0}  ,
    {"IABT"          , &configinput.IABTen               , 0}  ,
    {"InterABT"        , &configinput.InterABTen           , 0}  ,

    {"NumberReferenceFrames"  , &configinput.max_num_references   , 1}  ,
    {"AdaptiveRounding"    , &configinput.AdaptiveRounding      , 0}  ,
    {"AdaptRndWeightI"    , &configinput.AdaptRndWeight[0]      , 0}  ,
    {"AdaptRndWeightP"    , &configinput.AdaptRndWeight[1]      , 0}  ,
    {"AdaptRndWeightB"    , &configinput.AdaptRndWeight[2]      , 0}  ,
    {"AdaptRndWeightCrI"    , &configinput.AdaptRndWeight[3]    , 0}  ,
    {"AdaptRndWeightCrP"    , &configinput.AdaptRndWeight[4]    , 0}  ,
    {"AdaptRndWeightCrB"    , &configinput.AdaptRndWeight[5]    , 0}  ,

#ifdef RDO_Q
    {"UseRDO_Quant8"      , &configinput.UseRDO_Q8            , 0}  ,
    {"UseRDO_Quant16"      , &configinput.UseRDO_Q16           , 0}  ,
    {"UseRDO_Quant4"      , &configinput.UseRDO_Q4            , 0}  ,
#endif
#ifdef FastME
    {"FME"                    , &configinput.UseFME               , 0}  ,
    {"FMEDSR"                 , &configinput.DynamicSearchRange   , 0}  ,
    {"NoEarlyTermination"     , &configinput.NoET   , 0}  ,
    {"FMEScale"               , &configinput.FMEScale             , 0}  ,
#endif

    {NULL                     , NULL                              , -1}
};
/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static int para_name_to_map_index( char *s )
{
    int i = 0;

    while ( Map[i].TokenName != NULL )
        if ( 0 == strcmp( Map[i].TokenName, s ) )
            return i;
        else
            i++;

    return -1;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static char *get_config_file_content( char *Filename )
{
    unsigned FileSize;
    FILE *f;
    char *buf;

    if ( NULL == ( f = fopen( Filename, "r" ) ) )
    {
        snprintf( error_text, ET_SIZE, "Cannot open configuration file %s.\n", Filename );
        error( error_text, 300 );
    }

    if ( 0 != fseek( f, 0, SEEK_END ) )
    {
        snprintf( error_text, ET_SIZE, "Cannot fseek in configuration file %s.\n", Filename );
        error( error_text, 300 );
    }

    FileSize = ftell( f );

    if ( FileSize < 0 || FileSize > 60000 )
    {
        snprintf( error_text, ET_SIZE, "Unreasonable Filesize %d reported by ftell for configuration file %s.\n", FileSize, Filename );
        error( error_text, 300 );
    }

    if ( 0 != fseek( f, 0, SEEK_SET ) )
    {
        snprintf( error_text, ET_SIZE, "Cannot fseek in configuration file %s.\n", Filename );
        error( error_text, 300 );
    }

    if ( ( buf = malloc( FileSize + 1 ) ) == NULL )
        no_mem_exit( "get_config_file_content: buf" );


    FileSize = fread( buf, 1, FileSize, f );
    buf[FileSize] = '\0';

    fclose( f );

    return buf;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static void parse_content( char *buf, int bufsize )
{
    char *items[MAX_ITEMS_TO_PARSE];
    int MapIdx;
    int item = 0;
    int InString = 0;
    int InItem = 0;
    char *p = buf;
    char *bufend = &buf[bufsize];
    int IntContent;
    int i;


    while ( p < bufend )
    {
        switch ( *p )
        {
            case 13:
                p++;
                break;
            case '#':
                *p = '\0';
                while ( *p != '\n' && p < bufend )
                    p++;
                InString = 0;
                InItem = 0;
                break;
            case '\n':
                InItem = 0;
                InString = 0;
                *p++ = '\0';
                break;
            case ' ':
            case '\t':
                if ( InString )
                    p++;
                else
                {
                    *p++ = '\0';
                    InItem = 0;
                }
                break;
            case '"':
                *p++ = '\0';
                if ( !InString )
                {
                    items[item++] = p;
                    InItem = ~InItem;
                }
                else
                    InItem = 0;
                InString = ~InString;
                break;
            default:
                if ( !InItem )
                {
                    items[item++] = p;
                    InItem = ~InItem;
                }
                p++;
        }
    }

    item--;

    for ( i = 0; i < item; i += 3 )
    {
        if ( 0 > ( MapIdx = para_name_to_map_index( items[i] ) ) )
        {
            snprintf( error_text, ET_SIZE, " Parsing error in config file: Parameter Name '%s' not recognized.", items[i] );
            error( error_text, 300 );
        }
        if ( strcmp( "=", items[i + 1] ) )
        {
            snprintf( error_text, ET_SIZE, " Parsing error in config file: '=' expected as the second token in each line." );
            error( error_text, 300 );
        }
        switch ( Map[MapIdx].Type )
        {
            case 0:
                if ( 1 != sscanf( items[i + 2], "%d", &IntContent ) )
                {
                    snprintf( error_text, ET_SIZE, " Parsing error: Expected numerical value for Parameter of %s, found '%s'.", items[i], items[i + 2] );
                    error( error_text, 300 );
                }
                *( int * )( Map[MapIdx].Place ) = IntContent;
                printf( "." );
                break;
            case 1:
                strcpy( ( char * )Map[MapIdx].Place, items[i + 2] );
                printf( "." );
                break;
            default:
                assert( "Unknown value type in the map definition of configfile.h" );
        }
    }
    memcpy( input, &configinput, sizeof( input_t ) );
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static void profile_check()
{
    switch ( input->profile_id )
    {
        case 0x20:
        {
            if ( input->level_id != 0x10 && input->level_id != 0x20 && input->level_id != 0x22 && input->level_id != 0x40 && input->level_id != 0x42 && input->level_id != 0x44 )
            {
                printf( "\n Level_ID invalid or Unsupported. \n" );
                exit( -1 );
            }
            if ( input->chroma_format != 1 && input->chroma_format != 2 )
            {
                printf( "\n Chroma_format invaild.\n" );
                exit( -1 );
            }
            break;
        }
        case 0x40:
        case 0x42:
        case 0x22:
            printf( "\n Current Profile_ID is not 1.0 version. \n" );
            exit( -1 );
        default:
            printf( "\n Profile_ID invaild.\n" );
            exit( -1 );
    }
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
static void level_check()
{
    static const float frame_rate[8] = { 24000 / 1001, 24, 25, 30000 / 1001, 30, 50, 60000 / 1001, 60 };
    if ( input->frame_rate_code < 1 || input->frame_rate_code > 8 )
    {
        printf( "\n Undefined frame_rate in all levels. \n" );
        exit( 0 );
    }
    switch ( input->level_id )
    {
        case 0x10:
        case 0x11:
            if ( input->img_width > 352 )
            {
                printf( "\n Image Width exceeds level 2.0 restriction.\n" );
                exit( -1 );
            }
            else if ( input->img_height > 288 )
            {
                printf( "\n Image height exceeds level 2.0 restriction.\n" );
                exit( -1 );
            }
            else
            {
                if ( input->frame_rate_code > 5 )
                {
                    printf( "\n Current frame_rate is not support in Level_2.0 .\n" );
                    exit( -1 );
                }
                else
                {
                    if ( ( long )( input->img_width ) * ( long )( input->img_height ) * ( frame_rate[input->frame_rate_code - 1] ) > 2534400 )
                    {
                        printf( "\n Luma Sampling Rate invalid for level 2.0.\n" );
                        exit( -1 );
                    }
                }
            }
            if ( ( long )( input->img_width ) * ( long )( input->img_height ) / 256 > 396 )
            {
                printf( "\n The number of macroblock per frame exceeds 396 in level 2.0.\n" );
                exit( -1 );
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) * frame_rate[input->frame_rate_code - 1] / 256 > 11880 )
            {
                printf( " \n The number of macroblock per second exceeds 11880 in level 2.0.\n" );
                exit( -1 );
            }

            if ( input->chroma_format != 1 )
            {
                printf( "\n In level 2.0 only format 4:2:0 is supported.\n" );
                exit( -1 );
            }

            if ( input->level_id == 0x10 && input->bbv_buf_size > 122880 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }

            if ( input->level_id == 0x11 && input->bbv_buf_size > 311296 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }
            break;
        case 0x20:
            if ( input->img_width > 720 )
            {
                printf( "\n Image Width exceeds level 4.0's restriction.\n" );
                exit( -1 );
            }
            else if ( input->img_height > 576 )
            {
                printf( "\n Imgage Height exceeds level 4.0's restriction.\n" );
                exit( -1 );
            }
            else
            {
                if ( input->frame_rate_code > 5 )
                {
                    printf( "\n Current frame_rate is not support in Level_4.0 .\n" );
                    exit( -1 );
                }
                else
                {
                    if ( ( long )( input->img_width ) * ( long )( input->img_height ) * ( long )( frame_rate[input->frame_rate_code - 1] ) > 10368000 )
                    {
                        printf( "\n Luma Sampling Rate invalid for level 4.0.\n" );
                        exit( -1 );
                    }
                }
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) / 256 > 4050 )
            {
                printf( " \n The number of macroblock per frame exceeds 1,620 for Level_4.0.\n" );
                exit( -1 );
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) * frame_rate[input->frame_rate_code - 1] / 256 > 40500 )
            {
                printf( " \n The number of macroblock per second exceeds 40500 in Level_4.0.\n" );
                exit( -1 );
            }

            if ( input->chroma_format != 1 )
            {
                printf( "\n In level 4.0 only format 4:2:0 is supported.\n" );
                exit( -1 );
            }

            if ( input->bbv_buf_size > 1228800 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }
            break;
        case 0x22:
            if ( input->img_width > 720 )
            {
                printf( "\n Imgage Width exceeds level 4.2's restriction.\n" );
                exit( -1 );
            }
            else if ( input->img_height > 576 )
            {
                printf( "\n Image Height exceeds level 4.2's restriction.\n" );
                exit( -1 );
            }
            else
            {
                if ( input->frame_rate_code > 5 )
                {
                    printf( "\n Current frame_rate is not support in Level_4.2 .\n" );
                    exit( -1 );
                }
                else
                {
                    if ( ( long )( input->img_width ) * ( long )( input->img_height ) * ( long )( frame_rate[input->frame_rate_code - 1] ) > 10368000 )
                    {
                        printf( "\n Luma Sampling Rate invalid for level 4.2.\n" );
                        exit( -1 );
                    }
                }
            }
            if ( ( long )( input->img_width ) * ( long )( input->img_height ) / 256 > 1620 )
            {
                printf( " \n The number of macroblock per frame exceeds 1,620 for Level_4.2.\n" );
                exit( -1 );
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) * frame_rate[input->frame_rate_code - 1] / 256 > 40500 )
            {
                printf( " \n The number of macroblock per second exceeds 40500 in Level_4.2.\n" );
                exit( -1 );
            }

            if ( input->chroma_format != 1 && input->chroma_format != 2 )
            {
                printf( "\n In level 4.2 only format 4:2:0 and 4:2:2 are supported.\n" );
                exit( -1 );
            }

            if ( input->bbv_buf_size > 1851392 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }
            break;
        case 0x40:
        case 0x41:
            if ( input->img_width > 1920 )
            {
                printf( "\n Imgage Width exceeds level 6.0's restriction.\n" );
                exit( -1 );
            }
            else if ( input->img_height > 1152 )
            {
                printf( "\n Image Height exceeds level 6.0's restriction.\n" );
                exit( -1 );
            }
            else
            {
                if ( ( long )( input->img_width ) * ( long )( input->img_height ) * ( long )( frame_rate[input->frame_rate_code - 1] ) > 62668800 )
                {
                    printf( "\n Luma Sampling Rate invalid for level 6.0.\n" );
                    exit( -1 );
                }
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) / 256 > 8160 )
            {
                printf( " \n The number of macroblock per frame exceeds 8160 for Level_6.0.\n" );
                exit( -1 );
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) * frame_rate[input->frame_rate_code - 1] / 256 > 244800 )
            {
                printf( " \n The number of macroblock per second exceeds 244800 in Level_6.0.\n" );
                exit( -1 );
            }

            if ( input->chroma_format != 1 )
            {
                printf( "\n In level 6.0 only format 4:2:0 is supported.\n" );
                exit( -1 );
            }

            if ( input->level_id == 0x40 && input->bbv_buf_size > 2457600 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }

            if ( input->level_id == 0x41 && input->bbv_buf_size > 6144000 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }
            break;
        case 0x42:
            if ( input->img_width > 1920 )
            {
                printf( "\n Imgage Width exceeds level 6.2's restriction.\n" );
                exit( -1 );
            }
            else if ( input->img_height > 1152 )
            {
                printf( "\n Imgage Height exceeds level 6.2's restriction.\n" );
                exit( -1 );
            }
            else
            {
                if ( ( long )( input->img_width ) * ( long )( input->img_height ) * ( long )( frame_rate[input->frame_rate_code - 1] ) > 62668800 )
                {
                    printf( "\n Luma Sampling Rate invalid for level 6.2.\n" );
                    exit( -1 );
                }
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) / 256 > 8160 )
            {
                printf( " \n The number of macroblock per frame exceeds 8160 for Level_6.2.\n" );
                exit( -1 );
            }

            if ( ( long )( input->img_width ) * ( long )( input->img_height ) * frame_rate[input->frame_rate_code - 1] / 256 > 244800 )
            {
                printf( " \n The number of macroblock per second exceeds 244800 in Level_6.2.\n" );
                exit( -1 );
            }

            if ( input->chroma_format != 1 && input->chroma_format != 2 )
            {
                printf( "\n In level 6.2 only format 4:2:0 and 4:2:2 are supported.\n" );
                exit( -1 );
            }

            if ( input->bbv_buf_size > 3686400 )
            {
                printf( "\n Invalid Bbv_Buffer_Size input.\n" );
                exit( -1 );
            }
            break;
        case 0x44:
            break;

        default:
            printf( "\n No such level_ID. \n" );
            exit( -1 );
    }
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

static void patch_inp()
{
    input->fixed_pic_qp = 1;
    if ( input->qp_first > MAX_QP || input->qp_first < MIN_QP )
    {
        snprintf( error_text, ET_SIZE, "Error input parameter quant_0,check configuration file" );
        error( error_text, 400 );
    }

    if ( input->qp_p > MAX_QP || input->qp_p < MIN_QP )
    {
        snprintf( error_text, ET_SIZE, "Error input parameter quant_n,check configuration file" );
        error( error_text, 400 );
    }

    if ( input->qp_b > MAX_QP || input->qp_b < MIN_QP )
    {
        snprintf( error_text, ET_SIZE, "Error input parameter quant_B,check configuration file" );
        error( error_text, 400 );
    }


    if ( input->img_width % 16 != 0 )
    {
        img->auto_crop_right = 16 - ( input->img_width % 16 );
    }
    else
    {
        img->auto_crop_right = 0;
    }
    if ( 0 /*!input->progressive_sequence*/ )
    {
    }
    else
    {
        if ( input->img_height % 16 != 0 )
        {
            img->auto_crop_bottom = 16 - ( input->img_height % 16 );
        }
        else
        {
            img->auto_crop_bottom = 0;
        }
    }
    input->blk_size[0][0] = 16;
    input->blk_size[0][1] = 16;
    input->blk_size[1][0] = 16;
    input->blk_size[1][1] = 16;
    input->blk_size[2][0] = 8;
    input->blk_size[2][1] = 8;
    input->blk_size[3][0] = 4;
    input->blk_size[3][1] = 4;
    input->blk_size[4][0] = 16;
    input->blk_size[4][1] = 16;
    input->blk_size[5][0] = 4;
    input->blk_size[5][1] = 4;


    if ( input->succe_b > input->jumpd )
    {
        snprintf( error_text, ET_SIZE, "Number of B-frames %d can not exceed the number of frames skipped", input->succe_b );
        error( error_text, 400 );
    }

    if ( input->succe_b == 0 )
        input->low_delay = 1;
    else
        input->low_delay = 0;

    if ( strlen( input->in_file ) > 0 )
    {
        if ( ( p_in = open( input->in_file, O_RDONLY | O_BINARY ) ) == -1 )
        {
            snprintf( error_text, ET_SIZE, "Input file %s does not exist", input->in_file );
            error( error_text, 400 );
        }
        else
        {
            printf( "Input file %s opened\n", input->in_file );
        }
    }
    else
    {
        error( "Input file name length is empty", 400 );
    }

    //remove(input->recon_file);
    if ( strlen( input->recon_file ) > 0 && ( p_rec = open( input->recon_file,OPENFLAGS_WRITE,0x0100|0x0080 ) ) == -1 )
    {
        snprintf( error_text, ET_SIZE, "Error open file %s", input->recon_file );
    }

    p_trace = NULL;
#if TRACE
    if ( strlen( input->trace_file ) > 0 && ( p_trace = fopen( "traceenc.txt", "w+" ) ) == NULL )
    {
        snprintf( error_text, ET_SIZE, "Error open file %s", input->trace_file );
    }
#endif

    if ( input->seqheader_period != 0 && input->intra_period == 0 )
    {
        if ( input->intra_period == 0 )
            snprintf( error_text, ET_SIZE, "\nintra_period  should not equal %d when seqheader_period equal %d", input->intra_period, input->seqheader_period );
        error( error_text, 400 );
    }

    if ( input->seqheader_period == 0 && input->vec_period != 0 )
    {
        snprintf( error_text, ET_SIZE, "\nvec_period  should not equal %d when seqheader_period equal %d", input->intra_period, input->seqheader_period );
        error( error_text, 400 );
    }
    if ( input->slice_row_nr != 0 )
    {
        snprintf( error_text, ET_SIZE, "\n Slice Mode is note supported now" );
        error( error_text, 400 );
    }

    if ( input->bi_me == 1 && input->bi_me_refine == 0 )
    {
        snprintf( error_text, ET_SIZE, "\n BiPredMotionEstimation = 1 and BiPredMERefinements = 0 is not allowed." );
        error( error_text, 400 );
    }

    if ( input->UseRDO_Q16||input->UseRDO_Q8||input->UseRDO_Q4 )
        input->AdaptiveRounding=0;

    profile_check();
    level_check();
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void configure( int ac, char *av[] )
{
    char *content;
    int CLcount, ContentLen, NumberParams;

    memset( &configinput, 0, sizeof( input_t ) );

    CLcount = 1;
    while ( CLcount < ac )
    {
        if ( 0 == strncmp( av[CLcount], "-f", 2 ) )
        {
            content = get_config_file_content( av[CLcount + 1] );
            printf( "Parsing Configfile %s", av[CLcount + 1] );
            parse_content( content, strlen( content ) );
            printf( "\n" );
            free( content );
            CLcount += 2;
        }
        else
        {
            if ( 0 == strncmp( av[CLcount], "-p", 2 ) )
            {
                CLcount++;
                ContentLen = 0;
                NumberParams = CLcount;

                while ( NumberParams < ac && av[NumberParams][0] != '-' )
                    ContentLen += strlen( av[NumberParams++] );

                ContentLen += 1000;

                if ( ( content = malloc( ContentLen ) ) == NULL )
                    no_mem_exit( "configure: content" );

                content[0] = '\0';

                while ( CLcount < NumberParams )
                {
                    char *source = &av[CLcount][0];
                    char *destin = &content[strlen( content )];

                    while ( *source != '\0' )
                    {
                        if ( *source == '=' )
                        {
                            *destin++ = ' ';
                            *destin++ = '=';
                            *destin++ = ' ';
                        }
                        else
                            *destin++ = *source;
                        source++;
                    }
                    *destin = '\0';
                    CLcount++;
                }
                printf( "Parsing command line string '%s'", content );
                parse_content( content, strlen( content ) );
                free( content );
                printf( "\n" );
            }
            else
            {
                snprintf( error_text, ET_SIZE, "Error in command line, ac %d, around string '%s', missing -f or -p parameters?", CLcount, av[CLcount] );
                error( error_text, 300 );
            }
        }
    }
    patch_inp();
    printf( "\n" );
}

